package mr.ali.videoapp.portal.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.extern.slf4j.Slf4j;
import mr.ali.videoapp.portal.service.impl.WeChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 获取当前页面的url带参数
 */
@RestController
@CrossOrigin
@Slf4j
public class UrlLinkController {

    private final RestTemplate restTemplate = new RestTemplate();
    @Resource
    private WeChatService weChatService;
    @Autowired
    private ObjectMapper objectMapper;

    @PostMapping("/api/wx/generate-url-link")
    public ResponseEntity<Map<String, Object>> generateUrlLink(@RequestBody Map<String, Object> request) {
        try {
            log.info("收到生成 urllink 请求: {}", request);

            // 1. 提取参数
            String path = (String) request.get("path");
            String query = (String) request.get("query");
            String envVersion = (String) request.get("env_version");
            Integer expireType = (Integer) request.get("expire_type");
            Integer expireInterval = (Integer) request.get("expire_interval");

            // 2. 参数校验
            if (path != null && path.contains("?")) {
                throw new IllegalArgumentException("path cannot contain '?': " + path);
            }

            // 3. 构建请求体
            ObjectNode body = objectMapper.createObjectNode();
            if (path != null) {
                body.put("path", path);
            }
            body.put("query", query != null ? query.trim() : "");
            body.put("env_version", envVersion != null ? envVersion : "release");

            if (expireType != null) {
                body.put("expire_type", expireType);
                if (expireType == 0) {
                    Object expireTimeObj = request.get("expire_time");
                    if (expireTimeObj instanceof Number) {
                        body.put("expire_time", ((Number) expireTimeObj).longValue());
                    } else {
                        throw new IllegalArgumentException("expire_time must be a number (timestamp)");
                    }
                } else {
                    body.put("expire_interval", expireInterval != null ? expireInterval : 1);
                }
            }

            log.info("⚠️ 发送给微信的 JSON: {}", body);

            // 4. 调用微信接口
            String accessToken = weChatService.getAccessToken();
            String url = "https://api.weixin.qq.com/wxa/generate_urllink?access_token=" + accessToken;

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            HttpEntity<String> entity = new HttpEntity<>(body.toString(), headers);
            ResponseEntity<Map> response = restTemplate.postForEntity(url, entity, Map.class);

            log.info("✅ 微信返回: {}", response.getBody());
            return ResponseEntity.ok(response.getBody());

        } catch (Exception e) {
            log.error("生成 urllink 失败", e);
            return ResponseEntity.badRequest().body(null);
        }
    }
}